<template>
  <div>
    <el-row :gutter="10">
      <el-col :md="8" :lg="8">
        <div class="box-shadow pad10">
          <div class="head-container" style="display: flex">
            <el-button
              type="primary"
              v-if="UserInfo.Type == 3"
              @click="handleAdd()"
              >添加根级</el-button
            >
          </div>
          <div class="head-container">
            <el-tree
              :allow-drop="allowDrop"
              :data="classOptions"
              :props="props"
              :expand-on-click-node="false"
              ref="treeRef"
              node-key="ID"
              highlight-current
              :load="loadNode"
              lazy
              @node-click="handleNodeClick"
              @node-drop="handleDrop"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span>
                    <a
                      @click="handleEdit(data)"
                      style="color: #409eff"
                      v-if="UserInfo.Type == 3"
                    >
                      信息
                    </a>
                    <a
                      @click="handleAuth(data)"
                      v-if="UserInfo.Type == 3"
                      style="color: #409eff; margin-left: 10px"
                    >
                      权限
                    </a>
                    <a
                      @click="handleAdd(data)"
                      style="color: #409eff; margin-left: 10px"
                      v-if="UserInfo.Type == 3"
                    >
                      添加子集
                    </a>
                    <el-popconfirm
                      title="确定删除吗？"
                      @confirm="handleDeleteFolder(node, data)"
                    >
                      <template #reference>
                        <a
                          style="margin-left: 8px; color: red"
                          v-if="UserInfo.Type == 3"
                        >
                          删除
                        </a>
                      </template>
                    </el-popconfirm>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :md="16" :lg="16">
        <div class="box-shadow pad10" v-show="editInfo.ID">
          <MyTable
            :tableList="TableList"
            :columns="columns"
            v-model:page="page"
            :btnList="['delete']"
            @delete="handleDelete"
            @link="handleLink"
            :toolbar="false"
          >
            <template v-slot:tabTop>
              <div class="flex acenter">
                <div>
                  <el-button type="primary" @click="ShowChooseFile"
                    >上传文件</el-button
                  >
                </div>
                <div class="tcenter" style="width: 100%">
                  <div style="font-size: 16px; font-weight: bold">
                    {{ editInfo.Name }}
                  </div>
                  <div style="font-size: 14px; color: gray">
                    {{ editInfo.Remark }}
                  </div>
                </div>
              </div>
            </template>
          </MyTable>
        </div>
        <div v-show="!editInfo.ID" class="flex acenter" style="height: 100%">
          <div>请在左侧选择文件夹</div>
        </div>
      </el-col>
    </el-row>
    <MyDialog
      v-model:show="show"
      :title="title"
      :width="450"
      :formRef="formRef"
      @confirm="confirm"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        :label-width="80"
        ref="formRef"
        class="wid100"
      >
        <el-form-item label="上级层级">
          {{ currentName }}
        </el-form-item>
        <el-form-item label="名称" prop="Name">
          <el-input v-model="formData.Name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="Sort">
          <el-input-number
            v-model="formData.Sort"
            controls-position="right"
            :min="1"
          />
        </el-form-item>
        <el-form-item label="备注" prop="Remark">
          <el-input
            v-model="formData.Remark"
            type="textarea"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-form>
    </MyDialog>
    <MyDialog
      v-model:show="ShowChooseFileDialog"
      title="上传文件"
      :width="800"
      @confirm="SubmitUploadFile"
    >
      <MyTable
        :tableList="fileList"
        :columns="FileColumns"
        v-model:page="page"
        :btnList="['delete']"
        @delete="handleUploadFileDelete"
        @link="handleLink"
        :toolbar="false"
      >
        <template v-slot:tabTop>
          <FileUpload
            v-model:fileList="fileList"
            @getItem="handleGetItem"
            :showFile="false"
          ></FileUpload>
        </template>
      </MyTable>
    </MyDialog>
    <MyDialog
      v-model:show="ShowFileAuth"
      :title="title"
      :width="800"
      @confirm="SubmitFileAuth"
    >
      <MyTable
        :tableList="UserList"
        :columns="UserColumns"
        v-model:page="page"
        :btnList="['delete']"
        @delete="handleUserDelete"
        @link="handleLink"
        :toolbar="false"
      >
        <template v-slot:tabTop>
          <el-button type="primary" @click="handleAddAuthUser"
            >添加权限用户</el-button
          >
        </template>
      </MyTable>
      <MyTable
        :tableList="RoleList"
        :columns="RoleColumns"
        v-model:page="RolePage"
        :btnList="['delete']"
        @delete="handleUserDelete"
        @link="handleLink"
        :toolbar="false"
      >
        <template v-slot:tabTop>
          <el-button type="primary" @click="handleAddAuthRole"
            >添加权限角色</el-button
          >
        </template>
      </MyTable>
    </MyDialog>
    <!-- 选择用户 -->
    <MyDialog
      v-model:show="ShowChooseUser"
      title="选择用户"
      @confirm="SubmitBindUser"
      :destroy="true"
    >
      <UserTable
        :userColumns="AllUserColumns"
        v-model:checkList="ChooseUserList"
        :showAdd="false"
      ></UserTable>
    </MyDialog>
    <!-- 选择角色 -->
    <MyDialog
      v-model:show="ShowChooseRole"
      title="选择角色"
      @confirm="SubmitBindRole"
      :destroy="true"
    >
      <RoleTable
        v-model:checkList="ChooseRoleList"
        :RoleColumns="AllRoleColumns"
        :ShowAdd="false"
      ></RoleTable>
    </MyDialog>
  </div>
</template>

<script setup name="ClassFile">
import { getCurrentInstance, onMounted, ref, watch } from 'vue';
import {
  GetFolderRolesList_ID,
  GetFolderList_PID,
  SetFolderRoles,
  UploadFiles,
  DelFolder,
  AddOrUpdateFolder,
  GetFilesList_ID,
  DelFile
} from '@/api/school/file.js';
import useUserStore from '@/store/modules/user.js';
import UserTable from '@/views/system/User/index';
import RoleTable from '@/views/system/Role/index';
import { listRole } from '@/api/system/role';
const { proxy } = getCurrentInstance();
const UserInfo = computed(() => useUserStore().userInfo);
const ShowChooseUser = ref(false);
const classOptions = ref([]);
const editInfo = ref({});
const show = ref(false);
const title = ref('');
const rules = ref({
  Code: [{ required: true, message: '请输入', trigger: 'blur' }],
  Name: [{ required: true, message: '请输入', trigger: 'blur' }],
  Principal: [{ required: true, message: '请选择', trigger: 'blur' }]
});

const ShowChooseRole = ref(false);
const fileList = ref([]);
const AllRoleColumns = ref([
  { label: '多选框' },
  { label: '序号' },
  { label: '角色编号', prop: 'Code' },
  { label: '角色名称', prop: 'Name' },
  {
    label: '状态',

    tag: true,
    prop: 'tags'
  },
  { label: '创建时间', prop: 'CreateTime' },
  { label: '创建人', prop: 'CreateUser', user: true },
  { label: '最后更新时间', prop: 'UpdateTime' }
]);
const RoleColumns = ref([
  { label: '序号' },
  { label: '角色名称', role: true, prop: 'RoleName' },
  {
    label: '添加权限',
    prop: 'Add',
    switch: true,
    active: true,
    inactive: false
  },
  {
    label: '查询权限',
    prop: 'Search',
    switch: true,
    active: true,
    inactive: false
  }
]);
const UserColumns = ref([
  { label: '序号' },
  { label: '用户名称', prop: 'ID_User', user: true },
  {
    label: '添加权限',
    prop: 'Add',
    switch: true,
    active: true,
    inactive: false
  },
  {
    label: '查询权限',
    prop: 'Search',
    switch: true,
    active: true,
    inactive: false
  }
]);
const AllUserColumns = ref([
  { label: '多选框' },
  { label: '序号' },
  { label: '用户名称', prop: 'Name' },
  { label: '状态', tag: true, prop: 'tags' },
  { label: '电话号码', prop: 'Phone' },
  { label: '备注', prop: 'Remark', width: 300, input: true }
]);
const FileColumns = ref([
  { label: '序号' },
  { label: '文件名称', prop: 'Name', link: true },
  { label: '文件后缀', prop: 'Suffix', width: 100 },
  { label: '文件大小(kb)', prop: 'SizeKb' },
  { label: '附件备注', prop: 'Remark', input: true, width: 200 },
  { label: '操作' }
]);
const columns = ref([
  { label: '序号' },
  { label: '文件名称', prop: 'Name', link: true },
  { label: '文件后缀', prop: 'Suffix' },
  { label: '文件大小(kb)', prop: 'Size' },
  { label: '附件备注', prop: 'Remark' },
  { label: '操作', width: 160 }
]);
proxy.$formatKey(RoleColumns.value);
proxy.$formatKey(AllRoleColumns.value);
proxy.$formatKey(AllUserColumns.value);
proxy.$formatKey(UserColumns.value);
proxy.$formatKey(columns.value);
proxy.$formatKey(FileColumns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 99999
});
const UserPage = ref({
  PageIndex: 1,
  PageSize: 10
});
const RolePage = ref({
  PageIndex: 1,
  PageSize: 10
});
const formData = ref({});
const formRef = ref();
const ShowChooseFileDialog = ref(false);
const treeRef = ref();
const currentName = ref();
const ShowFileAuth = ref(false);
const ChooseUserList = ref([]);
const ChooseRoleList = ref([]);
const UserList = ref([]);
const RoleList = ref([]);
const AllRoleData = ref([]);
const props = {
  label: 'Name',
  children: 'children',
  isLeaf: 'isLeaf'
};
const TableList = ref([]);

onMounted(() => {
  getRoleList();
});

async function getRoleList() {
  try {
    let res = await listRole({
      PageIndex: 1,
      PageSize: 99999,
      Code: '', //模糊搜索
      Name: '' //模糊搜索
    });
    AllRoleData.value = res.data.List;
  } catch (error) {
    console.log(error);
  }
}

function handleAddAuthRole() {
  ChooseRoleList.value = RoleList.value;
  ShowChooseRole.value = true;
}

function handleAddAuthUser() {
  ChooseUserList.value = UserList.value;
  ShowChooseUser.value = true;
}

function SubmitBindRole() {
  let adds = RoleList.value?.filter(item => item.Add)?.map(item => item.ID);
  let searchs = RoleList.value
    ?.filter(item => item.Search)
    ?.map(item => item.ID);
  try {
    RoleList.value = ChooseRoleList.value?.map(item => {
      return {
        ID: item.ID,
        ID_User: '',
        ID_Role: item.ID,
        Search: searchs?.includes(item.ID),
        Add: adds?.includes(item.ID),
        RoleName: AllRoleData.value
          ?.filter(role => item.ID == role.ID)
          ?.map(role => role.Name)
      };
    });
    ShowChooseRole.value = false;
  } catch (error) {
    console.log(error);
  }
}

function SubmitBindUser() {
  let adds = UserList.value?.filter(item => item.Add)?.map(item => item.ID);
  let searchs = UserList.value
    ?.filter(item => item.Search)
    ?.map(item => item.ID);
  try {
    UserList.value = ChooseUserList.value?.map(item => {
      return {
        ID: item.ID,
        ID_User: item.ID,
        ID_Role: '',
        Search: searchs?.includes(item.ID),
        Add: adds?.includes(item.ID)
      };
    });
    ShowChooseUser.value = false;
  } catch (error) {
    console.log(error);
  }
}

async function confirm() {
  try {
    formRef.value.validate(async valid => {
      if (valid) {
        let query = {
          ...formData.value
        };
        if (title.value.includes('添加')) {
          let res = await AddOrUpdateFolder(query);
          proxy.$modal.msgSuccess('添加成功');
          if (formData.value.Pid != 0) {
            await SetFolderRoles({
              ID: res.data,
              Roles: [
                {
                  ID_User: UserInfo.value.ID, //用户ID
                  ID_Role: '', //角色ID
                  Search: 'true', //是否有权查看
                  Add: 'true' //是否有权添加
                }
              ]
            });
            let node = treeRef.value.getNode(query.Pid);
            node.loaded = false;
            node.loadData();
          } else {
            await SetFolderRoles({
              ID: res.data,
              Roles: [
                {
                  ID_User: UserInfo.value.ID, //用户ID
                  ID_Role: '', //角色ID
                  Search: 'true', //是否有权查看
                  Add: 'true' //是否有权添加
                }
              ]
            });
            treeRef.value.append({
              ...query,
              ID: res.data,
              isLeaf: true
            });
          }
        } else {
          let res = await AddOrUpdateFolder(query);
          let node = treeRef.value.getNode(query.ID);
          node.data = query;
          proxy.$modal.msgSuccess('编辑成功');
        }

        show.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

async function SubmitFileAuth() {
  try {
    let Users = UserList.value?.map(item => {
      return {
        ID_User: item.ID_User, //用户ID
        ID_Role: '', //角色ID
        Search: item.Search, //是否有权查看
        Add: item.Add //是否有权添加
      };
    });
    let Roles = RoleList.value?.map(item => {
      return {
        ID_User: '', //用户ID
        ID_Role: item.ID_Role, //角色ID
        Search: item.Search, //是否有权查看
        Add: item.Add //是否有权添加
      };
    });
    let query = {
      ID: editInfo.value.ID,
      Roles: [...Users, ...Roles]
    };
    await SetFolderRoles(query);
    proxy.$modal.msgSuccess('提交成功');
    ShowFileAuth.value = false;
  } catch (error) {
    console.log(error);
  }
}

function handleUserDelete(row) {
  UserList.value = UserList.value?.filter(item => item.ID != row.ID);
}

async function handleAuth(data) {
  try {
    editInfo.value = data;
    let res = await GetFolderRolesList_ID({ ID: data.ID });
    res.data.Users?.forEach(item => (item.ID = item.ID_User));
    res.data.Roles?.forEach(item => {
      item.ID = item.ID_Role;
      item.RoleName = AllRoleData.value
        ?.filter(role => item.ID_Role == role.ID)
        ?.map(role => role.Name);
    });
    UserList.value = res.data.Users;
    RoleList.value = res.data.Roles;
    title.value = '文件夹权限' + ' -- ' + data.Name;
    ShowFileAuth.value = true;
  } catch (error) {
    console.log(error);
  }
}

async function SubmitUploadFile() {
  try {
    let query = {
      FolderID: editInfo.value.ID,
      Files: fileList.value?.map(item => {
        return {
          FileID: item.ID, //文件ID
          Sort: '0', //排序
          Remark: item.Remark //说明备注
        };
      })
    };
    await UploadFiles(query);
    proxy.$modal.msgSuccess('上传成功');
    getFileList();
  } catch (error) {
    console.log(error);
  }
}

async function getFileList() {
  try {
    let res = await GetFilesList_ID({ ID: editInfo.value.ID });
    res.data?.forEach(item => {
      item.Size = Math.round(Number(item.Size / 1024));
    });
    TableList.value = res.data;
    ShowChooseFileDialog.value = false;
  } catch (error) {
    console.log(error);
  }
}

function handleLink(item) {
  let url = proxy.$addFileHead(item.Path);
  window.open(url);
}

function handleUploadFileDelete(row) {
  fileList.value = fileList.value?.filter(item => item.ID != row.ID);
}

function ShowChooseFile() {
  fileList.value = [];
  ShowChooseFileDialog.value = true;
}

async function handleGetItem(item) {
  if (!item && !item.length) return;
  try {
    console.log(item);
  } catch (error) {
    console.log(error);
  }
}

async function handleDelete(item) {
  try {
    await DelFile({ ID: item.ID });
    proxy.$modal.msgSuccess('删除成功');
    getFileList();
  } catch (error) {
    console.log(error);
  }
}

async function handleDeleteFolder(node, data) {
  try {
    await DelFolder({ ID: data.ID });
    proxy.$modal.msgSuccess('删除成功');
    treeRef.value.remove(node);
    if (data.ID == editInfo.value.ID) {
      editInfo.value = {};
    }
    show.value = false;
  } catch (error) {
    console.log(error);
  }
}

function allowDrop(draggingNode, dropNode, DropType) {
  return DropType == 'inner';
}

async function handleDrop(draggingNode, dropNode, dropType) {
  formData.value = proxy.$deepClone(draggingNode.data);
  formData.value.Pid = dropNode.data.ID;
  try {
    let query = {
      ...formData.value
    };
    await EditDept(query);
    console.log(dropNode);
    proxy.$modal.msgSuccess('修改成功');
    // treeRef.value.append(draggingNode, dropNode.data.ID);
  } catch (error) {
    console.log(error);
  }
}

async function loadNode(node, resolve) {
  try {
    let res;
    if (!node?.data?.ID) {
      res = await GetFolderList_PID({ ID: 0 });
    } else {
      res = await GetFolderList_PID({ ID: node.data.ID });
    }
    let list = res.data?.map(item => {
      return {
        ...item.Info,
        isLeaf: item.ChildFolderCount < 1
      };
    });
    resolve(list);
  } catch (error) {
    console.log(error);
  }
}

async function handleEdit(item) {
  title.value = '编辑文件夹';
  formData.value = {
    ...item
  };
  show.value = true;
}

function handleAdd(row) {
  show.value = true;
  if (row) {
    title.value = '添加子集';
    currentName.value = row.Name;
    formData.value = {
      Pid: row.ID,
      Sort: 1
    };
  } else {
    formData.value = {
      Pid: 0,
      Sort: 1
    };
    title.value = '添加根级';
  }
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.Name.indexOf(value) !== -1;
};
async function handleNodeClick(val) {
  // bindData.ID = val.ID
  editInfo.value = proxy.$deepClone(val);
  fileList.value = [];
  try {
    getFileList();
  } catch (error) {
    console.log(error);
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
